<?php
declare(strict_types=1);
namespace app\admin\widget;
use aphp\core\Widget;
class MakeTable extends Widget
{
    protected string $tag = 'model';
    protected int $expire = 0;
    public function set($id = '', array $options = []): array
    {
        $model = db('model')->field('id,table_name,table_prefix,table_comment,table_engine,table_charset,table_collate,table_primary')->where('table_name', $id)->find();
        if (!$model) {
            return [];
        }
        $model_field = db('model_field')->where('model_id', $model['id'])->where('status=1')->order('sort ASC,id ASC')->select();
        $field_set = []; // 字段设置
        foreach ($model_field as $field) {
            $field_set[] = $this->_parse_field($field); // 字段处理
        }
        if (!empty($field_set)) {
            $field_set[] = $this->_parse_primary(explode(',', $model['table_primary']));
            $model['table_fields'] =  implode(",\n", $field_set);
        }
        return $model;
    }

    // 处理字段
    private function _parse_field(array $vo): string
    {
        $str = '`' . $vo['field_name'] . '` ' . $vo['field_type'];
        if ($vo['field_length'] != '0' && $vo['field_type'] != 'text') {
            $str .= '(' . $vo['field_length'] . ')';
        }
        if ($vo['is_unsigned']) {
            $str .= ' UNSIGNED';
        }
        if ($vo['is_required'] == 1) {
            $str .= ' NOT NULL';
        }
        if ($vo['is_auto_increment']) {
            $str .= ' AUTO_INCREMENT';
        }
        if ($vo['field_value'] != 'null') {
            $str .= " DEFAULT '{$vo['field_value']}'";
        }
        return $str." COMMENT '{$vo['field_comment']}'";
    }

    // 处理主键
    private function _parse_primary(array $primary): string
    {
        $primary = array_map(fn($v)=>'`' . $v . '`', $primary);
        return 'PRIMARY KEY (' . implode(',', $primary) . ')';
    }
}